package com.wb.adutils.ads.pangle

import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.bytedance.sdk.openadsdk.*
import com.wb.adutils.AdBaseLoader
import com.wb.adutils.db.AdEntity
import com.wb.adutils.tools.AdConstants
import com.wb.adutils.tools.LogC
import java.lang.Exception


class PangleNativeAdUtils(val adEntity: AdEntity?): AdBaseLoader(adEntity) {

    private var gmaNativeAdList: ArrayList<TTNativeExpressAd>? = null

    override fun excLoadAd(activity: Activity) {
        //模板视频
       try {
           if (isAdLoadSuccess && gmaNativeAdList?.isNotEmpty() == true) {
               listener?.onAdLoaded(gmaNativeAdList)
               return
           }

            val mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity)
            val adSlot = AdSlot.Builder()
                .setCodeId(adEntity?.adUnit) //广告位id
                .setSupportDeepLink(false)
                .setAdCount(count) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(width * 1f, height * 1f) //期望模板广告view的size,单位dp
                .setAdLoadType(TTAdLoadType.LOAD) //推荐使用，用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，方便后续为开发者优化相关策略
                .build()
            //请求广告
            mTTAdNative.loadNativeExpressAd(adSlot, object : TTAdNative.NativeExpressAdListener {
                //广告请求失败
                override fun onError(code: Int, message: String) {
                    LogC.e("pangle -> 信息流广告 -> onAdLoadedFail...code=${code}, msg=${message}")
                    excAdLoadFail(code)
                }

                //广告请求成功
                override fun onNativeExpressAdLoad(ads: List<TTNativeExpressAd>) {
                    LogC.e("pangle -> 信息流广告 -> onNativeExpressAdLoad size：" + ads.size)
                    if (timeoutDisposable?.isDisposed == true) { // 已超时
                        LogC.e("pangle -> 信息流广告 -> onAdLoaded...但已超时...")
                        return
                    }
                    LogC.e("pangle -> 信息流广告 -> onAdLoaded..." + ads.size)
                    timeoutDisposable?.dispose()
                    isAdLoadSuccess = true
                    gmaNativeAdList?.clear()
                    if (ads.isEmpty()) {
                        listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_INTERNAL)
                        release()
                    } else {
                        gmaNativeAdList = ArrayList(ads)
                        listener?.onAdLoaded(ads)
                    }
                }
            })
           LogC.e("pangle -> 信息流广告 -> 准备开始加载广告...")
       } catch (e: Exception) {
           e.printStackTrace()
           timeoutDisposable?.dispose()
           listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_EXCEPTION)
           release()
       }
    }


    override fun showAd(adRoot: ViewGroup?) {
        LogC.e("pangle -> 信息流广告 -> showAd...")
        val activity = findActivity(adRoot?.context)
        if (adRoot == null || activity == null || activity.isDestroyed || activity.isFinishing) {
            release()
            return
        }
        if (gmaNativeAdList.isNullOrEmpty()) {
            listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_NOT_LOAD_SUCCESS)
            release()
            return
        }
        val nativeAd = gmaNativeAdList?.first()
        nativeAd?.setExpressInteractionListener(object : TTNativeExpressAd.ExpressAdInteractionListener {
            //广告点击回调
            override fun onAdClicked(view: View, type: Int) {
                LogC.e("pangle -> 信息流广告 -> showAd...onAdClick...")
                listener?.onAdClicked()
            }

            //广告展示回调
            override fun onAdShow(view: View, type: Int) {
                LogC.e("pangle -> 信息流广告 -> showAd...onAdShow...")
                listener?.onAdDisplay()
            }

            //广告渲染失败回调
            override fun onRenderFail(view: View, msg: String, code: Int) {
                LogC.e("pangle -> 信息流广告 -> showAd...onRenderFail...$code, $msg")
                listener?.onAdLoadFail(code)
                release()
            }

            //广告渲染成功回调
            override fun onRenderSuccess(view: View, width: Float, height: Float) {
                LogC.e("pangle -> 信息流广告 -> showAd...onRenderSuccess...$width x $height")
                adRoot.removeAllViews()
                adRoot.visibility = View.VISIBLE
                val layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT)
                adRoot.addView(nativeAd.expressAdView, layoutParams)
            }
        })
        //使用默认模板中默认dislike弹出样式
        nativeAd?.setDislikeCallback(activity, object : TTAdDislike.DislikeInteractionCallback {
            override fun onShow() {}
            override fun onCancel() {
                listener?.onAdLoadFail(AdConstants.AD_ERROR_CODE_USER_CANCEL)
                release()
            }
            override fun onSelected(position: Int, value: String, enforce: Boolean) {}
        })
        // 渲染广告
        nativeAd?.render()
    }


    override fun release() {
        super.release()
        gmaNativeAdList?.forEach {
            it.destroy()
        }
        gmaNativeAdList?.clear()
        gmaNativeAdList = null
    }


}